package com.siyoumi.app.modules.money.service;

import com.siyoumi.app.entity.SysMoneyRecord;
import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.modules.user.service.SvcSysUser;
import com.siyoumi.app.service.SysMoneyRecordService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@Service
public class SvcMoneyRecord {
    static public SvcMoneyRecord getBean() {
        return XSpringContext.getBean(SvcMoneyRecord.class);
    }

    static public SysMoneyRecordService getApp() {
        return SysMoneyRecordService.getBean();
    }

    public JoinWrapperPlus<SysMoneyRecord> getQuery(InputData inputData) {
        String openid = inputData.input("openid");
        String dateBegin = inputData.input("date_begin");
        String dateEnd = inputData.input("date_end");
        String desc = inputData.input("desc");
        String idSrc = inputData.input("id_src");
        String yyyyMM = inputData.input("yyyyMM");
        String abType = inputData.input("ab_type");

        JoinWrapperPlus<SysMoneyRecord> query = getQuery();
        if (XStr.hasAnyText(openid)) { // 昵称
            query.likeRight("mrec_openid", openid);
        }
        if (XStr.hasAnyText(desc)) { // 描述
            query.likeRight("mrec_desc", desc);
        }
        if (XStr.hasAnyText(idSrc)) { // 来源ID
            query.eq("mrec_id_src", idSrc);
        }
        if (XStr.hasAnyText(dateBegin) && XStr.hasAnyText(dateEnd)) { // 日期
            LocalDateTime b = XStr.toDateTime(dateBegin);
            LocalDateTime e = XStr.toDateTime(dateEnd);
            query.between("mrec_create_date", b, e);
        }
        if (XStr.hasAnyText(yyyyMM)) { // 月份
            LocalDateTime b = XStr.toDateTime(yyyyMM + "-01");
            LocalDateTime e = XStr.toDateTime(yyyyMM + "-01").plusMonths(1).minusSeconds(1);
            query.between("mrec_create_date", b, e);
        }
        if (XStr.hasAnyText(abType)) { //+或者-
            if ("-".equals(abType)) {
                query.lt("mrec_num", 0);
            } else {
                query.ge("mrec_num", 0);
            }
        }

        return query;
    }

    public JoinWrapperPlus<SysMoneyRecord> getQuery() {
        JoinWrapperPlus<SysMoneyRecord> query = getApp().join();
        query.eq("mrec_x_id", XHttpContext.getX());

        return query;
    }

    /**
     * 根据key获取
     *
     * @param key
     */
    public SysMoneyRecord getEntityByKey(String key) {
        JoinWrapperPlus<SysMoneyRecord> query = getApp().join();
        query.eq("mrec_x_id", XHttpContext.getX())
                .eq("mrec_uix", key);
        return getApp().first(query);
    }

    public SysMoneyRecord add(String key, String openid, String idSrc, String appId, BigDecimal num, String desc) {
        return add(key, openid, idSrc, appId, num, desc, null, null);
    }

    public SysMoneyRecord add(String key, String openid, String idSrc, String appId, BigDecimal num, String desc, String id00, String id01) {
        SysMoneyRecord entity = new SysMoneyRecord();
        entity.setMrec_x_id(XHttpContext.getX());
        entity.setMrec_uix(key);
        entity.setMrec_openid(openid);
        entity.setMrec_id_src(idSrc);
        entity.setMrec_app_id(appId);
        entity.setMrec_num(num);
        entity.setMrec_desc(desc);

        if (id00 != null) {
            entity.setMrec_id_00(id00);
        }
        if (id01 != null) {
            entity.setMrec_id_00(id01);
        }

        XApp.getTransaction().execute(status -> {
            boolean save = getApp().save(entity);
            if (entity.getMrec_num().compareTo(new BigDecimal("0")) > 0) {
                XLog.info(this.getClass(), "添加操作，更新用户总额");
            }

            return save;
        });

        return entity;
    }

    /**
     * 获取余额
     *
     * @param uid
     */
    public BigDecimal getMoney(String uid) {
        SysUser entityUser = SvcSysUser.getApp().first(uid);
        if (entityUser == null) {
            return BigDecimal.ZERO;
        }

        return entityUser.getUser_money();
    }

    /**
     * 更新用户余额，总收入
     *
     * @param uid
     * @param updateTotal true：
     */
    public BigDecimal updateMoney(String uid, boolean updateTotal) {
        JoinWrapperPlus<SysMoneyRecord> query = getQuery();
        query.eq("mrec_openid", uid);
        if (updateTotal) {
            query.gt("mrec_num", 0);
        }
        BigDecimal money = getApp().sum(query, "mrec_num");

        SysUser entityUser = SvcSysUser.getApp().first(uid);
        if (entityUser == null) {
            XValidator.err(EnumSys.ERR_VAL.getR("not find user"));
        }
        SysUser update = new SysUser();
        update.setUser_id(entityUser.getKey());
        if (updateTotal) {
            update.setUser_money_total(money);
        } else {
            update.setUser_money(money);
        }
        SvcSysUser.getApp().updateById(update);

        return money;
    }
}
